setwd("/Users/s.abi-hassan/Dropbox/OSU_WashU_NU Research Team/Downstream_cert/Replication_file") 
library(foreign)
#cases and justices data
load("SCDB_2015_01_justiceCentered_Docket.Rdata")
load("SCDB_2015_01_caseCentered_LegalProvision.RData")

#amicus briefs data
#load("ac-dataframe-edges-2000-2010.RData")
#load("ac-dataframe-vertices-2000-2010.RData")
#load("ac-net-2000-2010.RData")


#################################################################################################
############################------  DATA SETS  --------##########################################
#################################################################################################
#SPAETH DATA - JUSTICE CENTERED
justice <- SCDB_2015_01_justiceCentered_Docket

#convert dateDecision variable to character
justice$dateDecisionC <- as.character(justice$dateDecision)

#subset 1953-2012 by justice by docket - using Decision date
justice12 <- justice[which(justice$dateDecisionC >= "1953-10-01" 
                           & justice$dateDecisionC < "2013-06-30"),]

#recode justiceName variable to match network data
library(dplyr)
justiceName <- c("AFortas" = "Fortas",
                 "AJGoldberg" = "Goldberg",
                 "BRWhite" = "White",
                 "CEWhittaker" = "Whittaker",
                 "EWarren" = "Warren",
                 "FFrankfurter" = "Frankfurter",
                 "HABlackmun" = "Blackmun",
                 "HHBurton" = "Burton",
                 "HLBlack" = "Black",
                 "JHarlan2" = "Harlan2",
                 "LFPowell" = "Powell",
                 "PStewart" = "Stewart",
                 "RHJackson" = "Jackson",
                 "SFReed" = "Reed",
                 "SMinton" = "Minton",
                 "TCClark" = "Clark",
                 "TMarshall" = "Marshall",
                 "WEBurger" = "Burger",
                 "WJBrennan" = "Brennan",
                 "WODouglas" = "Douglas",
                 "WHRehnquist"="Rehnquist", 
                 "JPStevens"="Stevens",
                 "SDOConnor"="OConnor",
                 "AScalia"="Scalia",
                 "AMKennedy"="Kennedy",
                 "DHSouter"="Souter",
                 "CThomas"="Thomas",
                 "RBGinsburg"="Ginsburg",
                 "SGBreyer"="Breyer",
                 "JGRoberts"="Roberts",
                 "SAAlito"="Alito",
                 "SSotomayor"="Sotomayor", 
                 "EKagan" = "Kagan")

justice12$justiceName <- recode(justice12$justiceName, !!!justiceName)
detach("package:dplyr", unload = TRUE)
#---------------------------------------------------------------------------------
#SPAETH DATA - CASE CENTERED
case <- SCDB_2015_01_caseCentered_LegalProvision
case12 <- case[which(case$dateDecision >= "1953-10-01" & case$term < "2013-06-30"),]

case12 <- case12[which(case12$lawType != "NA"),]

#####################################################################################
########################## SCMQ IDEOLOGICAL MEASURES ################################
#####################################################################################
load("measures.Rdata")
#subset SCMQ - by decision date
measures12 <- measures[which(measures$term >= 1953 & measures$term <= 2012),]

#Relabel OConnor to match "justice10" data set
measures12$justiceName[measures12$justiceName == "O'Connor"] <- "OConnor"

#merge ideological measures to original dataset
justice12 <- merge(justice12, measures12, by=c("justiceName","term"), all.x=TRUE)

#################################################################################################
##################### ----------------- FORMAT DATE VARIABLES -----------------##################
#################################################################################################

justice12$dateDecision <- as.Date(justice12$dateDecision, origin="1953-10-12")
justice12$dateArgument <- as.Date(justice12$dateArgument, origin="1952-12-08")
justice12$dateDecisionC <- as.Date(justice12$dateDecisionC, origin="1953-10-12")

library(lubridate)
justice12$term <- as.Date(as.character(justice12$term), format = "%Y")
justice12$term <- year(justice12$term)
detach("package:lubridate", unload = TRUE)

##################################################################################################
################# ----------------- REVALUE MAJORITY OPINION WRITER ---------------###############
##################################################################################################
justice12$majOpinWriter[justice12$majOpinWriter=="78"] <- "Black"
justice12$majOpinWriter[justice12$majOpinWriter=="79"] <- "Reed"
justice12$majOpinWriter[justice12$majOpinWriter=="80"] <- "Frankfurter"
justice12$majOpinWriter[justice12$majOpinWriter=="81"] <- "Douglas"
justice12$majOpinWriter[justice12$majOpinWriter=="84"] <- "Jackson"
justice12$majOpinWriter[justice12$majOpinWriter=="86"] <- "Burton"
justice12$majOpinWriter[justice12$majOpinWriter=="88"] <- "Clark"
justice12$majOpinWriter[justice12$majOpinWriter=="89"] <- "Minton"
justice12$majOpinWriter[justice12$majOpinWriter=="90"] <- "Warren"
justice12$majOpinWriter[justice12$majOpinWriter=="91"] <- "Harlan2"
justice12$majOpinWriter[justice12$majOpinWriter=="92"] <- "Brennan"
justice12$majOpinWriter[justice12$majOpinWriter=="93"] <- "Whittaker"
justice12$majOpinWriter[justice12$majOpinWriter=="94"] <- "Stewart"
justice12$majOpinWriter[justice12$majOpinWriter=="95"] <- "White"
justice12$majOpinWriter[justice12$majOpinWriter=="96"] <- "Goldberg"
justice12$majOpinWriter[justice12$majOpinWriter=="97"] <- "Fortas"
justice12$majOpinWriter[justice12$majOpinWriter=="98"] <- "Marshall"
justice12$majOpinWriter[justice12$majOpinWriter=="99"] <- "Burger"
justice12$majOpinWriter[justice12$majOpinWriter=="100"] <- "Blackmun"
justice12$majOpinWriter[justice12$majOpinWriter=="101"] <- "Powell"
justice12$majOpinWriter[justice12$majOpinWriter=="102"] <- "Rehnquist"
justice12$majOpinWriter[justice12$majOpinWriter=="103"] <- "Stevens"
justice12$majOpinWriter[justice12$majOpinWriter=="104"] <- "OConnor"
justice12$majOpinWriter[justice12$majOpinWriter=="105"] <- "Scalia"
justice12$majOpinWriter[justice12$majOpinWriter=="106"] <- "Kennedy"
justice12$majOpinWriter[justice12$majOpinWriter=="107"] <- "Souter"
justice12$majOpinWriter[justice12$majOpinWriter=="108"] <- "Thomas"
justice12$majOpinWriter[justice12$majOpinWriter=="109"] <- "Ginsburg"
justice12$majOpinWriter[justice12$majOpinWriter=="110"] <- "Breyer"
justice12$majOpinWriter[justice12$majOpinWriter=="111"] <- "Roberts"
justice12$majOpinWriter[justice12$majOpinWriter=="112"] <- "Alito"
justice12$majOpinWriter[justice12$majOpinWriter=="113"] <- "Sotomayor"
justice12$majOpinWriter[justice12$majOpinWriter=="114"] <- "Kagan"

#################################################################################################
############################-------  DEPENDENT VARIABLE  --------################################
###############################------ JUSTICE'S VOTE --------####################################
justice12$choicedv <- justice12$vote

#recode variable
justice12$choicedv[justice12$choicedv==1] <- "Voted with Majority" #voted with majority
justice12$choicedv[justice12$choicedv==2] <- "Dissented" #dissented
justice12$choicedv[justice12$choicedv==3] <- "Regular Concurrence" #regular
justice12$choicedv[justice12$choicedv==4] <- "Special Concurrence" #special
justice12$choicedv[justice12$choicedv==5] <- NA #judgement of the court
justice12$choicedv[justice12$choicedv==6] <- NA #dissent from a denial or dissmisal of cert
justice12$choicedv[justice12$choicedv==7] <- NA #jurisdictional dissent
justice12$choicedv[justice12$choicedv==8] <- NA #justice participated in an equally divided vote

##################################################################################################
#####################------------- IDEOLOGICAL DISTANCE -----------------#########################
##################################################################################################
#new data frame w/mq scores for majority opinion writers ideology variable
majOpin.mq <- measures12
majOpin.mq$justice <- NULL #delete repeated variable
majOpin.mq$scQual <- NULL
majOpin.mq$scIdeology <- NULL
names(majOpin.mq)[names(majOpin.mq) == 'justiceName'] <- 'majOpinWriter' #rename variable of match
names(majOpin.mq)[names(majOpin.mq) == 'mqScore'] <- 'mq.ScoreMaj' #rename variable of interest

#merge mq.score for majority opinion writer
justice12 <- merge(justice12, majOpin.mq, by=c("term", "majOpinWriter"), all.x=TRUE)
justice12$mq.ScoreMaj[is.na(justice12$mq.ScoreMaj)] <- 0

#mq.scoresabsolute value
justice12$abs.mqScore <- abs(justice12$mqScore)
justice12$abs.mqScoreMaj <- abs(justice12$mq.ScoreMaj)

#ideological difference variable
justice12$iddistance <- abs(justice12$abs.mqScore - justice12$abs.mqScoreMaj)
head(justice12$iddistance)

################################################################################################
########################--------- LEGAL COMPLEXITY VARIABLE ------------########################
################################################################################################
#factor analysis of the number of issues raised in the case and number of legal 
#provision relevant to the case

#new data frame with legal provision only
legal <- data.frame(case12$caseId, case12$lawType) 
names(legal)[names(legal) == 'case12.caseId'] <- 'caseId'
names(legal)[names(legal) == 'case12.lawType'] <- 'lawType'

#new data frame for issue area only
issue <- data.frame(case12$caseId, case12$issueArea)
names(issue)[names(issue) == 'case12.caseId'] <- 'caseId'
names(issue)[names(issue) == 'case12.issueArea'] <- 'issueArea'

#count unique values
library(plyr)
legal.unique <- count(unique(legal))
law.count <- count(legal.unique, vars="caseId", wt_var="freq")
names(law.count)[names(law.count) == 'freq'] <- 'lawCount'

issue.unique <- count(unique(issue))
issue.count <- count(issue.unique, vars="caseId", wt_var="freq")
names(issue.count)[names(issue.count) == 'freq'] <- 'issueCount'

legalComp <- merge(law.count, issue.count, by=c('caseId'), all=TRUE)
detach("package:plyr", unload = TRUE)

#-------------------------------------------------------------------------
#factor analysis of number of legal provision and issues raised in a case
library(psych)
#calculate correlation matrix
legalComp$caseId <- NULL
corMat <- cor(legalComp, legalComp)

#eigenvalues
ev <- eigen(cor(legalComp))
ev

#exploratory factor analysis
legalfa <- fa(r=corMat, nfactors = 1, rotate="oblimin", fm="pa")
legalfa
legalfa1 <- fa(r=corMat, nfactors = 1, rotate="oblimin", fm="ml")
legalfa1

#prinicipal axis factor analysis scores
legalscores <- factor.scores(legalComp, legalfa, Phi = NULL, method = c("tenBerge"),rho=NULL)
summary(legalscores)

legalscores1 <- factor.scores(legalComp, legalfa1, Phi = NULL, method = c("Thurstone"),rho=NULL)
summary(legalscores1)

#add legal complexity scores to legal Comp
legalComp$legalscores <- legalscores[["scores"]]
legalComp$legalscores1 <- legalscores1[["scores"]]

legalComp$caseId <- law.count$caseId

#merging adjustments - w/justice12
justice12 <- merge(justice12, legalComp, by=c("caseId"), all.x=TRUE)

#remove repeated rows
justice12 <- unique(justice12)

detach("package:psych", unload = TRUE)

###########################################################################################
############################ SALIENCE TO THE PUBLIC DATA FRAME ############################
###########################################################################################
load("CLRSalienceEstimates100714.RData")
salience12 <- salienceEstimates[,c(1,4)]
names(salience12)[names(salience12) == 'salienceData.caseId'] <- 'caseId'
names(salience12)[names(salience12) == 'salience.est'] <- 'salience'

justice12 <- merge(justice12, salience12, by="caseId", all.x=TRUE)

###################################################################################################
########################--------- LEGAL SALIENCE VARIABLE -------------############################
###################################################################################################
#recode declared unconstitutional to binary
justice12$declarationUncon[justice12$declarationUncon == 1] <- 0
justice12$declarationUncon[justice12$declarationUncon == 2] <- 1 
justice12$declarationUncon[justice12$declarationUncon == 3] <- 1 
justice12$declarationUncon[justice12$declarationUncon == 4] <- 1 
head(justice12$declarationUncon)

justice12$legalSalience <- ifelse(justice12$precedentAlteration == 1, 1,
                                  ifelse(justice12$declarationUncon == 1, 1, 0))

#################################################################################################
##########################--------- COOPERATION VARIABLE ------------############################
#################################################################################################
#measures extent to which past cooperation influences a justices behavior
#percenttJoin = number of times the majority opinion writer joined a special 
#opinion written by another justice in the previous term
#cooperation = #residuals after regression of percentage join on iddistance

#biMaj = 1 when majority opinion writer
justice12$biMaj <- ifelse(justice12$majOpinWriter == justice12$justiceName, 1, 0)

#########
#majority opinion 
maj <- data.frame("justiceName" = justice12$justiceName, 
                  "term" = justice12$term, 
                  "biMaj" = justice12$biMaj, 
                  "caseId" = justice12$caseId)

maj$term1 <- maj$term - 1

maj <- maj[which(maj$biMaj > 0),]

library(dplyr)
#data frame with majority writers
coop_maj <- data.frame("justiceName" = justice12$justiceName, 
                       "term" = justice12$term, 
                       "firstAgreement" = justice12$firstAgreement)

coop_maj <- unique(coop_maj)

#turn NAs to 0
coop_maj <- replace(coop_maj, is.na(coop_maj), 0)

coop_maj <- coop_maj[which(coop_maj$firstAgreement > 0),]

coop_maj <- coop_maj %>%
  group_by(justiceName, term) %>%
  summarise(sep = n())

save(coop_maj, file="coop_maj.RData")
#####################################################################
coop_maj1 <- data.frame("justiceName" = justice12$justiceName, 
                        "term" = justice12$term, 
                        "secondAgreement" = justice12$secondAgreement)

coop_maj1 <- unique(coop_maj1)

#turn NAs to 0
coop_maj1 <- replace(coop_maj1, is.na(coop_maj1),0)

coop_maj1 <- coop_maj1[which(coop_maj1$secondAgreement > 0),]

coop_maj1 <- coop_maj1 %>%
  group_by(justiceName, term) %>%
  summarise(sep = n())

####
coop_pair <- merge(coop_maj, coop_maj1, by=c("justiceName", "term"), all=TRUE)
coop_pair <- replace(coop_pair, is.na(coop_pair),0)

coop_pair$sep <- coop_pair$sep.x + coop_pair$sep.y

#########################################################################
#calculate number of special opinions
spec_opinion <- data.frame("term" = justice12$term, 
                           "caseId" = justice12$caseId,
                           "justiceName" = justice12$justiceName,
                           "choicedv" = justice12$choicedv)

spec_opinion$spec <- ifelse(spec_opinion$choicedv == "Voted with Majority", 0, 1) 
spec_opinion[is.na(spec_opinion)] <- 0

coop_opinion_count <- data.frame("term" = spec_opinion$term,
                                 "spec" = spec_opinion$spec)
coop_opinion_count <- coop_opinion_count[which(coop_opinion_count$spec > 0),]

coop_opinion_count <- coop_opinion_count %>%
  group_by(term) %>%
  summarise(spec_count = sum(spec))

########################################
coop_pair$sep.x <- NULL
coop_pair$sep.y <- NULL

#merge count of separate opinions by justice with total number of separate opinions by year
coop_pair <- merge(coop_pair, coop_opinion_count, by="term", all.x = TRUE)
coop_pair$percJoin <- (coop_pair$sep/coop_pair$spec_count)*100

names(coop_pair)[names(coop_pair) == 'term'] <- 'term1'


#merge two datasets for final tally
cooperation <- merge(maj, coop_pair, by=c("term1", "justiceName"), all.x=TRUE)
cooperation$term1 <- NULL
cooperation[is.na(cooperation)] <- 0
#save(cooperation, file = "cooperation.RData")

#merge with main data set 
justice12 <- merge(justice12, cooperation, by=c("caseId"), all.x=TRUE)
justice12 <- unique(justice12)
detach("package:dplyr", unload = TRUE)

names(justice12)[names(justice12) == 'term.x'] <- 'term'
names(justice12)[names(justice12) == 'justiceName.x'] <- 'justiceName'
names(justice12)[names(justice12) == 'biMaj.x'] <- 'biMaj'
names(justice12)[names(justice12) == 'justice.x'] <- 'justice'

#################################################################################################
############################--------- FRESHMAN VARIABLE -------------############################
#################################################################################################
justice12$initTerm <- justice12$justiceName

#recode each justice to its initial term
justice12$initTerm[justice12$initTerm == "Fortas"] <- 1965
justice12$initTerm[justice12$initTerm == "Goldberg"] <- 1962
justice12$initTerm[justice12$initTerm == "White"] <- 1962
justice12$initTerm[justice12$initTerm == "Whittaker"] <- 1957
justice12$initTerm[justice12$initTerm == "Warren"] <- 1953
justice12$initTerm[justice12$initTerm == "Frankfurter"] <- 1957
justice12$initTerm[justice12$initTerm == "Blackmun"] <- 1970
justice12$initTerm[justice12$initTerm == "Burton"] <- 1945
justice12$initTerm[justice12$initTerm == "Black"] <- 1937
justice12$initTerm[justice12$initTerm == "Harlan2"] <- 1955
justice12$initTerm[justice12$initTerm == "Powell"] <- 1972
justice12$initTerm[justice12$initTerm == "Stewart"] <- 1958
justice12$initTerm[justice12$initTerm == "Jackson"] <- 1941
justice12$initTerm[justice12$initTerm == "Reed"] <- 1938
justice12$initTerm[justice12$initTerm == "Minton"] <- 1949
justice12$initTerm[justice12$initTerm == "Clark"] <- 1949
justice12$initTerm[justice12$initTerm == "Marshall"] <- 1967
justice12$initTerm[justice12$initTerm == "Burger"] <- 1969
justice12$initTerm[justice12$initTerm == "Brennan"] <- 1956
justice12$initTerm[justice12$initTerm == "Douglas"] <- 1939
justice12$initTerm[justice12$initTerm == "Rehnquist"] <- 1973
justice12$initTerm[justice12$initTerm == "Stevens"] <- 1976
justice12$initTerm[justice12$initTerm == "OConnor"] <- 1981
justice12$initTerm[justice12$initTerm == "Scalia"] <- 1986
justice12$initTerm[justice12$initTerm == "Kennedy"] <- 1989
justice12$initTerm[justice12$initTerm == "Souter"] <- 1990
justice12$initTerm[justice12$initTerm == "Thomas"] <- 1991
justice12$initTerm[justice12$initTerm == "Ginsburg"] <- 1993
justice12$initTerm[justice12$initTerm == "Breyer"] <- 1994
justice12$initTerm[justice12$initTerm == "Roberts"] <- 2005
justice12$initTerm[justice12$initTerm == "Alito"] <- 2007
justice12$initTerm[justice12$initTerm == "Sotomayor"] <- 2009
justice12$initTerm[justice12$initTerm == "Kagan"] <- 2010
table(justice12$initTerm)

justice12$initTerm <- as.numeric(justice12$initTerm)
justice12$frosh <- justice12$term - justice12$initTerm
table(justice12$frosh)

#recode frosh to binary
justice12$frosh[justice12$frosh <= 2] <- 1
justice12$frosh[justice12$frosh > 2] <- 0

table(justice12$frosh)
head(justice12$frosh)


##################################################################################################
#########################--------- CHIEF JUSTICE VARIABLE -------------###########################
##################################################################################################

justice12$chiefJustice <- ifelse(justice12$justiceName == justice12$chief, 1, 0)
table(justice12$chiefJustice)


################################################################################################
#####################--------- DATASET WITH CONTROL VARIABLES ----------##################
################################################################################################

justice12F <- data.frame("caseId" = justice12$caseId, 
                         "term" = justice12$term,
                         "docket" = justice12$docket,
                         "docketId" = justice12$docketId,
                         "caseName" = justice12$caseName,
                         "justiceName" = justice12$justiceName,
                         "chief" = justice12$chief,
                         "majOpinWriter" = justice12$majOpinWriter,
                         "certReason" = justice12$certReason,
                         "lcDisagreement" = justice12$lcDisagreement,
                         "declarationUncon" = justice12$declarationUncon,
                         "precedentAlt" = justice12$precedentAlteration,
                         "partyWinning" = justice12$partyWinning,
                         "lawType" = justice12$lawType,
                         "lawSupp" = justice12$lawSupp,
                         "lawCount" = justice12$lawCount,
                         "issueArea" = justice12$issueArea,
                         "issueCount" = justice12$issueCount,
                         "choicedv" = justice12$choicedv,
                         "iddistance" = justice12$iddistance,
                         "justIdeology" = justice12$mqScore,
                         "legalScores" = justice12$legalscores[ ,1],
                         "legalScores1" = justice12$legalscores1[ ,1],
                         "legalSalience" = justice12$legalSalience,
                         "pubSalience" = justice12$early.salience.est,
                         "percJoin" = justice12$percJoin,
                         "frosh" = justice12$frosh,
                         "chiefJustice" = justice12$chiefJustice,
                         "win" = justice12$partyWinning,
                         "decisionDirection" = justice12$decisionDirection)

#remove majority opinion writer. 
justice12F <- subset(justice12F, majOpinWriter != justiceName)
justice12F <- unique(justice12F)

#####################################################################
#regress percentage joined on ideological distance
justice12F$percJoin[is.na(justice12F$percJoin)] <- 0
summary(justice12F$iddistance)
justice12F$iddistance[is.na(justice12F$iddistance)] <- 1.466
mod.coop <- lm(percJoin ~ iddistance, data=justice12F)
summary(mod.coop)
justice12F$resCoop <- mod.coop$resid


############
#factor dependent variable
justice12F$choicedv <- factor(justice12F$choicedv, 
                              levels = c("Voted with Majority", "Regular Concurrence", 
                                         "Special Concurrence", "Dissented"))

#majority - minority
justice12F$majMin <- ifelse(justice12F$choicedv == "Dissented", 0, 1)

#binary dependent variable 
justice12F$bi_choicedv <- ifelse(justice12F$choicedv == "Voted with Majority", 0,
                                 ifelse(justice12F$choicedv == "Regular Concurrence", 1,
                                        ifelse(justice12F$choicedv == "Special Concurrence", 1,
                                               ifelse(justice12F$choicedv == "Dissented", 1, NA))))

#################################################################################
save(justice12F, file="justice12F.RData")

####################################################################################
##################------------- NUMBER OF AMICUS BRIEFS --------------##############
#####################################################################################
case12F <- data.frame("caseId" = case12$caseId,
                      "term" = case12$term,
                      "win" = case12$partyWinning,
                      "declarationUncon" = case12$declarationUncon,
                      "precedentAlt" = case12$precedentAlteration)

load("SignersBriefs.RData")
signersBriefs <- data.frame("caseId" = signersBriefs$caseId,
                            "briefId" = signersBriefs$briefId,
                            "direction" = signersBriefs$direction)

direction <- merge(case12F, signersBriefs, by="caseId", all.x = TRUE)
direction <- unique(direction)

direction <- direction[complete.cases(direction),]

#count of briefs by case
library(dplyr)
totBriefs <- direction %>%
  group_by(caseId) %>%
  summarize(num_totBriefs = n())

#conver NAs to zeros
totBriefs$num_totBriefs[is.na(totBriefs$num_totBriefs)] <- 0

#merge with Spaeth data frame
justice12F <- merge(justice12F, totBriefs, by=c("caseId"), all.x=TRUE)
justice12F <- unique(justice12F)

library(dplyr)
justice12F <- justice12F %>% 
  mutate(st_num_totBriefs = scale(num_totBriefs))

#######################################################################################
#####################--------- HETEROGENEITY VAIRIABLES --------#######################
#######################################################################################
load("aggSic.RData")

#create new data frames with count of SICs per case 
sicCountT <- data.frame("caseId" = aggSic$caseId, 
                        "sicTot" = aggSic$sic2)

#count unique SICs per case per side (petitioner v respondent)
sicCountT <- sicCountT[complete.cases(sicCountT),]
sicCountT <- unique(sicCountT)

library(dplyr)
totsic <- sicCountT %>%
  group_by(caseId) %>%
  summarize(totsic = n())

#load("totsic.RData")
justice12F <- merge(justice12F, totsic, by = c("caseId"), all.x = TRUE)

justice12F <- unique(justice12F)
#save(justice12, file = "justice12.RData")

#dichotomous heterogeneity variable - threshold third quartile
summary(justice12F$totsic)
justice12F$dich_totsic <- ifelse(justice12F$totsic >= 2, 1, 0)


######################################################################################
###########################--------- POWER VARIABLES ---------########################
######################################################################################
load("group_Direc.RData")

bcTot <- data.frame("caseId" = group_Direc$caseId, 
                    "briefId" = group_Direc$briefId,
                    "bpowTot" = group_Direc$power,
                    "bcentTot" = group_Direc$central)

bcTot <- bcTot[which(complete.cases(bcTot)),]

#extract max centrality values
library(dplyr)
bcTot <- bcTot %>%
  group_by(caseId) %>%
  summarize_at(c("bcentTot", "bpowTot"), max, na.rm=TRUE)

summary(bcTot$bcentTot)
bcTot$dich_bcentTot <- ifelse(bcTot$bcentTot >= 0.085, 1, 0)

#merge with justice12F
justice12F <- merge(justice12F, bcTot, by=c("caseId"), all.x=TRUE)
justice12F <- unique(justice12F)

#####################################################################################
#################### limit data to time frame of interest ###########################
#####################################################################################
justice86F_cert <- justice12F[which(justice12F$term >= 1986 
                                    & justice12F$term < 1995),]

#####################################################################################
###################------- MAIN EXPLANATORY VARIABLES -------########################
#####################################################################################
load("justice_cert.RData")

justice86F_cert <- merge(justice86F_cert, justice_cert, by=c("caseId", "justiceName", "term", "docket"), 
                         all=TRUE)

justice86F_cert$bi_certVote <- ifelse(justice86F_cert$certVote == "G", 1,
                                      ifelse(justice86F_cert$certVote == "D", 0, NA))

justice86F_cert <- unique(justice86F_cert)

# Convert empty strings to NA
justice86F_cert[justice86F_cert == ""] <- NA

######################################################################################
########################## CATEGORICAL REASON FOR CERT ###############################
####
justice86F_cert$certDumb1 <- ifelse(justice86F_cert$certReason == 10, 2,
                                    ifelse(justice86F_cert$certReason >= 2 & 
                                             justice86F_cert$certReason <= 9, 1, 0))
#######################################################################################
############################# JUSTICE VOTE ON THE MERITS ##############################
#######################################################################################
justice86F_cert$majMin <- ifelse(justice86F_cert$choicedv == "Dissented", 0, 1)

justice86F_cert$vote <- ifelse(justice86F_cert$win == 1 & justice86F_cert$majMin == 1, "reverse",
                               ifelse(justice86F_cert$win == 1 & justice86F_cert$majMin == 0, "affirm",
                                      ifelse(justice86F_cert$win == 0 & justice86F_cert$majMin == 1, "affirm", 
                                             ifelse(justice86F_cert$win == 0 & justice86F_cert$majMin == 0, "reverse", 
                                                    NA))))

justice86F_cert$vote <- factor(justice86F_cert$vote, 
                               levels = c("affirm", "reverse"))

#######################################################################################
justice86F_cert <- unique(justice86F_cert)
justice86F_cert$num_totBriefs[is.na(justice86F_cert$num_totBriefs)] <- 0
justice86F_cert$totsic[is.na(justice86F_cert$totsic)] <- 0
justice86F_cert$dich_totsic[is.na(justice86F_cert$dich_totsic)] <- 0
justice86F_cert$dich_bcentTot[is.na(justice86F_cert$bcentTot)] <- 0

library(haven)
save(justice86F_cert, file="justice86F_cert.RData")
write_dta(justice86F_cert, "justice86F_cert.dta")

######################################################################################
#Figure 1. Cosigner Network by Group Power
library(GGally)
library(network)
library(sna)
library(intergraph)

ggnet2(g)
set.seed(112183)
ggnet2(g, node.size = 0.6, node.color = "blue", edge.size = .1, edge.color = "grey")


#######################################################################################
#Figure 2. Histograms of Group SIC Heterogeneity by Case
library(ggplot2)
library(dplyr)
library(tidyr)


hist <- justice86F_cert %>%
  filter(totsic != 0) %>%
  ggplot(aes(totsic)) + 
  geom_histogram(breaks=seq(0,10, by=1), 
                 col="darkgrey", 
                 aes(fill=..count..)) +
  theme_light() +
  scale_fill_gradient("Count", low="darkgreen", high="orange") +
  labs(title="", x="Total SICs per Case", y="Number of Cases") +
  theme(panel.border=element_blank(),
        legend.position = "right",
        legend.title = element_blank(),
        legend.box.spacing = unit(1, "mm"),
        axis.title.y=element_text(size=12, hjust=0.5, vjust=4),
        axis.text.y=element_text(size=10), 
        axis.text.x=element_text(size=10),
        legend.text=element_text(size=10)) +
  guides(color=guide_legend(ncol=1, byrow=FALSE)) +
  theme(plot.margin = unit(c(.5,.5,.5,.5), "cm")) +
  scale_x_continuous(breaks=c(0,1,2,3,4,5,6,7,8,9,10)) +
  scale_y_continuous(breaks=seq(0, 3000, by=500), 
                     limits=c(0, 3000))

hist

#EOF
#---EOF
